package com.starview.star.compiler.format.rules;

import java.util.Map;
import java.util.Map.Entry;

import com.starview.platform.data.type.Location;
import com.starview.star.compiler.ast.IAbstract;
import com.starview.star.compiler.ast.IAttribute;
import com.starview.star.compiler.format.BaseAttribute;
import com.starview.star.compiler.standard.StandardNames;
import com.starview.star.compiler.util.PrettyPrintDisplay;

@SuppressWarnings("serial")
public class FmtAttributes implements FmtFormatOp
{
  private final Map<String, IAttribute> attributes;

  public FmtAttributes(Location loc, Map<String, IAttribute> attributes)
  {
    this.attributes = attributes;
  }

  @SuppressWarnings("rawtypes")
  @Override
  public void format(IAbstract term, Location loc, IAbstract[] env)
  {
    for (Entry<String, IAttribute> entry : attributes.entrySet()) {
      String att = entry.getKey();
      IAttribute attribute = entry.getValue();

      if (term.hasAttribute(att)) {
        IAttribute existing = term.getAttribute(att);
        if (((BaseAttribute) existing).getSpecificity() < ((BaseAttribute) attribute).getSpecificity())
          term.setAttribute(att, attribute);
      } else
        term.setAttribute(att, attribute);
    }
  }

  @Override
  public void prettyPrint(PrettyPrintDisplay disp)
  {
    disp.append("{");
    int mark = disp.markIndent(2);
    String sep = "";
    for (Entry<String, IAttribute> entry : attributes.entrySet()) {
      disp.append(sep);
      sep = ";\n";
      disp.appendWord(entry.getKey());
      disp.append(StandardNames.COLON);
      entry.getValue().prettyPrint(disp);
    }
    disp.popIndent(mark);
    disp.append("}");
  }
}
